//
//  EMSFeedBackViewController.m
//  yunyan
//
//  Created by chirui on 2018/6/22.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "EMSFeedBackViewController.h"
#import "WSImagePickerView.h"

#define kScreenWidth        [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight       [[UIScreen mainScreen] bounds].size.height
@interface EMSFeedBackViewController (){
    
    NSArray * imageArray;
}
@property (nonatomic,strong) SZTextView * messageSztTextView;

@property (nonatomic, strong) WSImagePickerView *pickerView;

@property (nonatomic,strong) UIButton * sureBtn;

@end

@implementation EMSFeedBackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self customNaviItemTitle:@"信箱留言" isLeft:YES];
    [self creatUi];
}

-(void)creatUi{
    
    UIView * photoView = [[UIView alloc]initWithFrame:CGRectMake(10, 10, WIDTH-20, 255)];
    photoView.layer.cornerRadius = 4.f;
    photoView.layer.masksToBounds = YES;
    photoView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:photoView];
    
    
    
    self.messageSztTextView =[[SZTextView alloc]initWithFrame:CGRectMake(10, 10, WIDTH-20, 110)];
    self.messageSztTextView.placeholder = @"请写下您想对我们说的话(500字以内)";
    self.messageSztTextView.placeholderTextColor = [UIColor lightGrayColor];
    self.messageSztTextView.font =[UIFont systemFontOfSize:15];
    [photoView addSubview:self.messageSztTextView];
    
    UILabel * messageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 110, WIDTH -20, 20)];
    messageLabel.text = @"  注：最多选择六张照片";
    messageLabel.font = [UIFont systemFontOfSize:13];
    messageLabel.textColor = [UIColor lightGrayColor];
    [photoView addSubview:messageLabel];
    
    WSImagePickerConfig *config = [WSImagePickerConfig new];
    config.itemSize = CGSizeMake(50, 50);
    config.photosMaxCount = 6;
    
    WSImagePickerView *pickerView = [[WSImagePickerView alloc] initWithFrame:CGRectMake(0, 130, kScreenWidth-20, 0) config:config];
    //Height changed with photo selection
    //    __weak typeof(self) weakSelf = self;
    
    //    NSLayoutConstraint *photoViewHieghtConstraint = [nsla]
    //
    //    pickerView.viewHeightChanged = ^(CGFloat height) {
    //        weakSelf.photoViewHieghtConstraint.constant = height;
    //        [weakSelf.view setNeedsLayout];
    //        [weakSelf.view layoutIfNeeded];
    //    };
    pickerView.navigationController = self.navigationController;
    [photoView addSubview:pickerView];
    self.pickerView = pickerView;
    
    //refresh superview height
    [pickerView refreshImagePickerViewWithPhotoArray:nil];
    
    //确定按钮
    self.sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sureBtn.frame = CGRectMake(15, CGRectGetMaxY(photoView.frame)+20, WIDTH -30, 50);
    self.sureBtn.backgroundColor = RGBA(81, 158, 238, 1);
    self.sureBtn.enabled =YES;
    self.sureBtn.layer.masksToBounds = YES;
    self.sureBtn.layer.cornerRadius = 5;
    [self.sureBtn setTitle: @"发布" forState:UIControlStateNormal];
    [self.sureBtn addTarget:self action:@selector(sureBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.sureBtn];
    
}

-(void)sureBtnClicked{
      imageArray = [_pickerView getPhotos];
    
    if (_messageSztTextView.text.length<6||_messageSztTextView.text==nil) {
        
        SHuiMBhudTextTimeStr(@"留言内容不能小于6个字");
        
    }else {
        
        [self RequestForMessage:_messageSztTextView.text];
    }
}

-(void)RequestForMessage:(NSString  *)messge{
    
    NSLog(@"self.imageArray = %@",imageArray);
    
    NSString *jsonString;
    NSMutableArray * img = @[].mutableCopy;
    if (img) {
        [img removeAllObjects];
    }
    if (imageArray.count>0) {
        for (int i = 0; i<imageArray.count; i++) {
            
            NSData *data = UIImageJPEGRepresentation(imageArray[i], 0.3);
            NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            NSString * imageStr = [NSString stringWithFormat:@"data:image/png;base64,%@",encodedImageStr];
            
            [img addObject:imageStr];
        }
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:img
                                                           options:kNilOptions
                                                             error:nil];
        
        jsonString = [[NSString alloc] initWithData:jsonData
                                           encoding:NSUTF8StringEncoding];
    }else{
        
        jsonString = @"";
    }
    
    
    NSDictionary * dic = @{
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"content": messge,
                           @"img":jsonString
                           };
    SHuiMBhudTextTimeStr(@"正在加载");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(mailBox_message_api ) andparameters:dic Success:^(id responseObject) {
        
        SHuiMBhudTextTimeStr(@"留言成功");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.navigationController popViewControllerAnimated:YES];
        });
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"操作频繁，请稍后再试");
        }else if(responses.statusCode == 403){
            SHuiMBhudTextTimeStr(@"操作频繁，请稍后再试");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
}

@end

